/** 
Copyright (c) 2010, Sheikh Abdul Wahid Ahmed
Details @ http://extremecodeworld.codeplex.com/license
**/

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Collections.Generic;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using EXtremecode.BusinessLayer;
using EXtremecode.PresentationLayer;
using EXtremecode.Utils;
using EXtremecode.Common;
using System.Text;
using System.IO;
using EXtremecode.Logging;
using EXtremecode.DataAccessLayer;
/// <summary>
/// Summary description for ParentPage
/// </summary>
namespace EXtremecode.PresentationLayer
{

    
    public class ParentPage : System.Web.UI.Page
    {
        private IPage page;
        private bool readMessagesOn = true;

        public ParentPage()
            : base()
        {
            if (!(this is IPage))
            {
                throw new Exception("Page should implement IPage interface");
            }
            page = this as IPage;
        }
        protected bool ReadMessagesOn
        {
            get
            {
                return readMessagesOn;
            }
            set
            {
                readMessagesOn = value;
            }
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
        }
        protected bool IsPopup
        {
            get
            {
                return (Request.QueryString["IsPopup"] != null && Request.QueryString["IsPopup"] == "1");
            }
        }
        protected override void OnPreInit(EventArgs e)
        {
            
            base.OnPreInit(e);
            if (!CheckSecurity())
            {
                Response.Redirect(FormsAuthentication.LoginUrl+ "?unauthorized=true", true);
            }
            else
            {
                if (IsPopup)
                {
                    Page.MasterPageFile = ResourceProvider.GetGeneralResourceString("URL_PopupMasterPage");
                }
                else
                {
                    Page.MasterPageFile = ResourceProvider.GetGeneralResourceString("URL_DefaultMasterPage");
                }
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            MultiView mvMessage = page.MVMessage;

            if (mvMessage != null && ReadMessagesOn)
            {
                mvMessage.Visible = false;

                View viewError = mvMessage.FindControl("viewError") as View;
                View viewInfo = mvMessage.FindControl("viewInformation") as View;

                string errorMessage = (!string.IsNullOrEmpty(ErrorMessage)) ? ErrorMessage : GeneralErrorMessage;
                string information = (!string.IsNullOrEmpty(Information)) ? Information : GeneralInformation;

                if (!string.IsNullOrEmpty(errorMessage))
                {
                    Label lbl = viewError.FindControl("lblError") as Label;

                    if (lbl != null)
                    {
                        lbl.Text = errorMessage;
                        mvMessage.Visible = true;
                        mvMessage.SetActiveView(viewError);
                    }
                }
                else if (!string.IsNullOrEmpty(information))
                {
                    Label lbl = viewInfo.FindControl("lblInformation") as Label;
                    if (lbl != null)
                    {
                        lbl.Text = information;

                        mvMessage.Visible = true;
                        mvMessage.SetActiveView(viewInfo);
                    }
                }

                //consume messages
                ErrorMessage = string.Empty;
                Information = string.Empty;
                GeneralErrorMessage  = string.Empty;
                GeneralInformation  = string.Empty;
            }


            base.OnPreRender(e);
        }
        protected virtual string PageKey
        {
            get
            {
                return page.EntityName; 
            }
        }
        protected virtual bool CheckSecurity()
        {
            IUserProfile profile = SessionRepository.Instance.UserProfile;

            if (profile == null || profile.User == null)
            {
                string userName = (SessionRepository.Instance["LoggedInUserName"] == null)? string.Empty:
                        SessionRepository.Instance["LoggedInUserName"].ToString();
                Logger.Write(string.Format("UserName:{0} ",userName));
            }
            return (profile != null && profile.User != null &&
                profile.User.IsUserAuthorizedForModule(PageKey));
        }

        protected string ErrorMessage
        {
            get
            {
                return SessionRepository.Instance["ErrorMessage_" + page.EntityName] as string;
            }
            set
            {
                SessionRepository.Instance["ErrorMessage_" + page.EntityName] = value;
            }
        }
        protected string Information
        {
            get
            {
                return SessionRepository.Instance["Information_" + page.EntityName] as string;
            }
            set
            {
                SessionRepository.Instance["Information_" + page.EntityName] = value;
            }
        }

        protected string GeneralErrorMessage
        {
            get
            {
                return SessionRepository.Instance["GeneralErrorMessage_"] as string;
            }
            set
            {
                SessionRepository.Instance["GeneralErrorMessage_"] = value;
            }
        }
        protected string GeneralInformation
        {
            get
            {
                return SessionRepository.Instance["GeneralInformation_"] as string;
            }
            set
            {
                SessionRepository.Instance["GeneralInformation_"] = value;
            }
        }
        protected void RedirectTo(string url,bool endResponse)
        {
            try
            {
                Response.Redirect(url, endResponse);
            }
            catch
            {}
            finally
            {
                ReadMessagesOn = false;
            }
        }
        protected void RedirectTo(string url)
        {
            RedirectTo(url, false);
        }

        protected void RedirectTo()
        {
            RedirectTo(Request.RawUrl, false);
        }

        public Control FindControlRecursive(string id)
        {
            return FindControlRecursive(null,id);
        }

        public Control FindControlRecursive(Control root, string id)
        {
            if (root == null)
            {
                root = this; 
            }

            if (root.ID == id)
            {
                return root;
            }
            foreach (Control ctl in root.Controls)
            {
                //ignore grids.
                if (ctl is CompositeDataBoundControl)
                {
                    continue;
                }
                
                Control foundCtl = FindControlRecursive(ctl, id);

                if (foundCtl != null)

                    return foundCtl;

            }



            return null;

        }

    }
}